import java.lang.reflect.Constructor;

/**
        * Created with IntelliJ IDEA.
        * Description:
        * User: GAOBO
        * Date: 2020-02-24
        * Time: 16:13
        */
public enum TestEnum {
    RED("red",1),BLACK("black",2),WHITE("white",3),GREEN("green",4);
    private String name;
    private int key;
/**
 * 1、当枚举对象有参数后，需要提供相应的构造函数
 * 2、枚举的构造函数默认是私有的 这个一定要记住
 * @param name
 * @param key
 */
private TestEnum (String name,int key) {
    this.name = name;
    this.key = key;
}

    public static TestEnum getEnumKey (int key) {
        for (TestEnum t: TestEnum.values()) {
            if(t.key == key) {
                return t;
            }
        }
        return null;
    }
    public static void reflectPrivateConstructor() {
        try {
            Class<?> classStudent = Class.forName("TestEnum");
//注意传入对应的参数,获得对应的构造方法来构造对象,当前枚举类是提供了两个参数分别是String和int。
            Constructor<?> declaredConstructorStudent = classStudent.getDeclaredConstructor(String.class,int.class);
//设置为true后可修改访问权限
            declaredConstructorStudent.setAccessible(true);
            Object objectStudent = declaredConstructorStudent.newInstance("绿色",666);
            TestEnum testEnum = (TestEnum) objectStudent;
            System.out.println("获得枚举的私有构造函数："+testEnum);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    public static void reflectPrivateConstructor() {
        try {
            Class<?> classStudent = Class.forName("TestEnum");
//注意传入对应的参数,获得对应的构造方法来构造对象,当前枚举类是提供了两个参数分别是String和int。
            Constructor<?> declaredConstructorStudent =
                    classStudent.getDeclaredConstructor(String.class,int.class,String.class,int.class);
//设置为true后可修改访问权限
            declaredConstructorStudent.setAccessible(true);
//后两个为子类参数，大家可以将当前枚举类的key类型改为double验证
            Object objectStudent = declaredConstructorStudent.newInstance("父类参数",666,"子类参数",888);
            TestEnum testEnum = (TestEnum) objectStudent;
            System.out.println("获得枚举的私有构造函数："+testEnum);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    public static void main(String[] args) {
        reflectPrivateConstructor();
    }
}

